package com.movecar.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.MoveCarInfoBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.PopupWindowAnimation;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.AsyncImageLoader;
import com.movecar.widget.CustomProgressDialog;
import com.movecar.widget.MoveCarImageview;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 
 * 更多-挪车相关
 * 
 * @author Zhao.JQ
 */
public class MoveCarsActivity extends Activity implements OnClickListener {

	private EditText carNumber;
	private TextView car_type;
	private RelativeLayout car_type_layout;
	private String mCarType = "0";
	MoveCarInfoBean mMoveCarInfoBean;
	private CustomProgressDialog progressDialog = null;
	CloudBeansBean mCloudBeansBean;
	private ImageLoader imageLoader = null;
	private MoveCarImageview mImageView;
	private View mainView;
	private LayoutInflater layoutInflater;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);mainView = layoutInflater.inflate(R.layout.more_move_car, null);
		setContentView(mainView);
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		initView();
		startProgressDialog();
		getInfoData();
	}

	private void initView() {

		carNumber = (EditText) findViewById(R.id.carNumber);
		car_type = (TextView) findViewById(R.id.car_type);
		car_type_layout = (RelativeLayout) findViewById(R.id.car_type_layout);
		new Thread() {

			@Override
			public void run() {

				super.run();
				try {
					Bitmap mBitmap = AsyncImageLoader.loadImageFromUrl(AppConfig.HOST + "/pages/files/addCarImg.png");
					// 获得SharedPreferences对象
					SharedPreferences preferences = getSharedPreferences("img", 0);
					int widthx = Integer.parseInt(preferences.getString("width", "").equals("") ? "0" : preferences
							.getString("width", ""));

					// 获得可编辑对象
					SharedPreferences.Editor editor = preferences.edit();
					editor.putString("width", String.valueOf(mBitmap.getWidth()));
					editor.putString("hight", String.valueOf(mBitmap.getHeight()));
					editor.commit();
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);

				} catch (Exception e) {
					e.printStackTrace();
				}

			}

		}.start();

		car_type_layout.setOnClickListener(this);
		findViewById(R.id.ok).setOnClickListener(this);
		findViewById(R.id.cancel).setOnClickListener(this);
		;
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);

		back.setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("挪车服务");

	}

	final Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				mImageView = (MoveCarImageview) findViewById(R.id.img_info);
				imageLoader.displayImage(AppConfig.HOST + "/pages/files/addCarImg.png", mImageView);

				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;
		case R.id.ok:

			if (!"".equals(carNumber.getText().toString().trim())) {
				startProgressDialog();
				setInfoData();
			} else {
				Alert.info(MoveCarsActivity.this, "请输入车牌号");

			}
			break;
		case R.id.car_type_layout:
			new AlertDialog.Builder(this).setItems(new String[] { "蓝牌白字（小型车）", "蓝牌黑字（大型车）" },
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							switch (which) {
							case 0:
								mCarType = "0";
								car_type.setText("蓝牌白字（小型车）");
								break;
							case 1:
								mCarType = "1";
								car_type.setText("蓝牌黑字（大型车）");
								break;

							default:
								break;
							}
						}
					}).show();
			break;
		case R.id.cancel:
			startProgressDialog();
			cancelService();
			break;
		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void getInfoData() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryCarNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();

				try {
					mMoveCarInfoBean = gson.fromJson(result, MoveCarInfoBean.class);
				} catch (Exception e) {
					return;
				}

				if ("".equals(mMoveCarInfoBean.getError()) || null == mMoveCarInfoBean.getError()) {
					if ("".equals(mMoveCarInfoBean.getFail()) || null == mMoveCarInfoBean.getFail()) {
						if (!"".equals(mMoveCarInfoBean.getCarNum()) && null != mMoveCarInfoBean.getCarNum()) {
							carNumber.setText(mMoveCarInfoBean.getCarNum());
							if ("0".equals(mMoveCarInfoBean.getCarType())) {
								car_type.setText("蓝牌白字（小型车）");
							} else {
								car_type.setText("蓝牌黑字（大型车）");
							}

						} else {
							mMoveCarInfoBean.setCarId("");
							Alert.info(MoveCarsActivity.this, "您目前没有绑定车辆");
						}

					} else {
						Alert.info(MoveCarsActivity.this, mMoveCarInfoBean.getFail());
					}
				} else {
					Alert.info(MoveCarsActivity.this, mMoveCarInfoBean.getError());
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.info(MoveCarsActivity.this, "与服务器连接失败，请检查网络");

			}
		}, MoveCarInfoBean.class, AppConfig.USER).execute(params);
	}

	@SuppressWarnings("unchecked")
	private void setInfoData() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "addOrUpdateCarNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("carNum", carNumber.getText().toString()));
		params.add(new BasicNameValuePair("carType", mCarType));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();

				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mCloudBeansBean) {
					if ("0".equals(mCloudBeansBean.getResultCode())) {
						if (!TextUtils.isEmpty(mCloudBeansBean.getCoinAlert())) {
							new PopupWindowAnimation(mainView, MoveCarsActivity.this);
						}
						Alert.info(MoveCarsActivity.this, "绑定成功");
						finish();

					} else {
						Alert.info(MoveCarsActivity.this, "绑定失败");
					}

				} else {
					Alert.info(MoveCarsActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.info(MoveCarsActivity.this, "与服务器连接失败，请检查网络");

			}
		}, CloudBeansBean.class, AppConfig.USER).execute(params);
	}

	@SuppressWarnings("unchecked")
	private void cancelService() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "unbindCarNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();

				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mCloudBeansBean) {
					if ("0".equals(mCloudBeansBean.getResultCode())) {
						if (!TextUtils.isEmpty(mCloudBeansBean.getCoinAlert())) {
							new PopupWindowAnimation(mainView, MoveCarsActivity.this);
						}
						Alert.info(MoveCarsActivity.this, "解除绑定成功");
						finish();

					} else {
						Alert.info(MoveCarsActivity.this, "绑定失败");
					}

				} else {
					Alert.info(MoveCarsActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.info(MoveCarsActivity.this, "与服务器连接失败，请检查网络");

			}
		}, MoveCarInfoBean.class, AppConfig.USER).execute(params);
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
